#include "stm32f10x.h"
#include "freertos.h"
#include "task.h"
#include "UART1.h"
#include "UART2.h"
#include "UART3.h"
#include <string.h>
#include "flash.h"
#include "System_reset.h"
#include "ADC.h"
// Flash存储配置
volatile uint8_t reset_key_pressed = 0;
volatile uint32_t reset_press_time = 0;
#define FLASH_START_ADDR 0x0800FC00  // STM32F103C8T6最后一页
#define FLASH_PAGE_SIZE  0x400       // 1KB每页

QueueHandle_t queue;
FlashConfig_t flash_config;

void convert(const char* in, char* out);


// 退出透传模式函数
void exit_transparent_mode() {
    // 发送退出透传指令(连续发送3个+)
    printf2("+++");
    vTaskDelay(pdMS_TO_TICKS(1000));  // 等待退出透传模式
}

// 连接WiFi函数
int connect_wifi(const char* ssid, const char* pwd) {
    char cmd[50];
    char buf[200] = {0};

    // 发送连接指令
    sprintf(cmd, "AT+CWJAP_DEF=\"%s\",\"%s\"\r\n", ssid, pwd);
    printf3("Connecting WiFi: %s", cmd);
    printf2("%s", cmd);

    // 等待连接结果
    while (1) {
        char ch = 0;
        BaseType_t ret = xQueueReceive(queue, &ch, pdMS_TO_TICKS(5000));

        if (ret == pdFAIL) {
            printf3("WiFi connect timeout\r\n");
            return 0;
        } else {
            buf[strlen(buf)] = ch;

            if (strstr(buf, "OK") != NULL) {
                printf3("WiFi connected successfully\r\n");
                return 1;  // 连接成功
            }

            if (strstr(buf, "ERROR") != NULL) {
                printf3("WiFi connect failed: %s\r\n", cmd);
                return 0;  // 连接失败
            }
        }
    }
}

// 建立TCP连接函数
int connect_tcp() {
    char buf[200] = {0};

    printf3("TCP connect :AT+CIPSTART=\"TCP\",\"47.115.220.165\",9030\r\n");
    printf2("AT+CIPSTART=\"TCP\",\"47.115.220.165\",9030\r\n");

    while (1) {
        char ch = 0;
        BaseType_t ret = xQueueReceive(queue, &ch, pdMS_TO_TICKS(5000));

        if (ret == pdFAIL) {
            printf3("TCP connect timeout\r\n");
            return 0;
        } else {
            buf[strlen(buf)] = ch;

            if (strstr(buf, "OK") != NULL) {
                printf3("TCP connected: %s\r\n", buf);
                return 1;
            }

            if (strstr(buf, "ERROR") != NULL) {
                printf3("TCP connect failed: %s\r\n", buf);
                return 0;
            }
        }
    }
}

// 进入透传模式函数
int enter_transparent_mode() {
    char buf[200] = {0};

    // 开启透传模式
    printf3("send touchuan:AT+CIPMODE=1\r\n");
    printf2("AT+CIPMODE=1\r\n");
    memset(buf, 0, sizeof(buf));

    while (1) {
        char ch = 0;
        BaseType_t ret = xQueueReceive(queue, &ch, pdMS_TO_TICKS(2000));

        if (ret == pdFAIL) {
            printf3("Set transparent mode timeout\r\n");
            return 0;
        } else {
            buf[strlen(buf)] = ch;

            if (strstr(buf, "OK") != NULL) {
                printf3("Transparent mode enabled: %s\r\n", buf);
                break;
            }
        }
    }

    // 开始发送数据
    printf3("start data send and receive:AT+CIPSEND\r\n");
    printf2("AT+CIPSEND\r\n");
    memset(buf, 0, sizeof(buf));

    while (1) {
        char ch = 0;
        BaseType_t ret = xQueueReceive(queue, &ch, pdMS_TO_TICKS(2000));

        if (ret == pdFAIL) {
            printf3("Start send data timeout\r\n");
            return 0;
        } else {
            buf[strlen(buf)] = ch;

            if (strstr(buf, "OK") != NULL || strstr(buf, ">") != NULL) {
                printf3("Ready to transmit: %s\r\n", buf);
                return 1;
            }
        }
    }
}
#define CONFIG_MAGIC 0x55AA55AA
int flag=0;
void task1(void * arg) {
    char buf[100] = {0};
    if (flash_config.is_configured) {
        printf3("Found saved config, connecting directly...\r\n");

        // 先退出透传模式(防止复位后仍在透传模式)
        exit_transparent_mode();
		
        // 直接使用保存的配置连接
		Flash_ReadConfig(&flash_config);
        if (connect_wifi(flash_config.ssid, flash_config.pwd) &&
                connect_tcp() &&
                enter_transparent_mode()) {
            // 连接成功，进入数据收发循环
            goto data_transmission_loop;
        } else {
            printf3("Connection failed, waiting for new config...\r\n");
            flash_config.is_configured = 0;  // 标记配置无效
            Flash_WriteConfig(&flash_config);
			
        }
    }

    // 没有有效配置，等待蓝牙发送数据
    printf3("Waiting for configuration via Bluetooth...\r\n");
    while (1) {
		
        char ch = 0;
        BaseType_t ret = xQueueReceive(queue, &ch, pdMS_TO_TICKS(1000));
        if (ret == pdFAIL) {
            continue;
        } else {
            // 收到数据
            if (flag < 2) {
                buf[strlen(buf)] = ch;
//				 printf3("Bluetooth config received: %s\r\n", buf);
                if (ch == '!') {
                    flag++;
                }
            }
        }
        if (flag == 2) {
            printf3("Bluetooth config received: %s\r\n", buf);

            char out[100] = {0};
            convert(buf, out);

            // 临时提取SSID
            char temp_ssid[50] = {0};
            char temp_pwd[50] = {0};
			sscanf(out, "AT+CWJAP_DEF=\"%49[^\"]\",\"%49[^\"]\"\r\n", 
			temp_ssid, temp_pwd);
            // 连接WiFi
            printf3("ESP01S config: %s", out);
            printf2("%s", out);
            memset(buf, 0, sizeof(buf));

            // 等待WiFi连接成功
            while (1) {
                char ch = 0;
                BaseType_t ret = xQueueReceive(queue, &ch, pdMS_TO_TICKS(1000));

                if (ret == pdFAIL) {
                    continue;
                } else {
                    buf[strlen(buf)] = ch;
                }

                if (strstr(buf, "OK") != NULL) {
                    printf3("WiFi connected: %s\r\n", buf);
                    memset(buf, 0, sizeof(buf));
                    strcpy(flash_config.ssid, temp_ssid);
                    strcpy(flash_config.pwd, temp_pwd);
                    flash_config.is_configured = 1;
					flash_config.magic=CONFIG_MAGIC;
                    Flash_WriteConfig(&flash_config);
					//验证存进去的数据真实性
                    printf3("Config saved to Flash\r\n");
					printf3("name:%s,pwd:%s,%d\r\n",flash_config.ssid,flash_config.pwd,flash_config.is_configured);
					Flash_ReadConfig(&flash_config);
//					while(1){}
                    break;
                }
            }

            // 只有连接成功，才保存配置到 Flash


            // 建立TCP连接
            if (!connect_tcp()) {
                printf3("TCP connection failed, restarting...\r\n");
                vTaskDelay(pdMS_TO_TICKS(1000));
                NVIC_SystemReset();  // 重置系统
            }

            // 进入透传模式
            if (!enter_transparent_mode()) {
                printf3("Enter transparent mode failed, restarting...\r\n");
                vTaskDelay(pdMS_TO_TICKS(1000));
                NVIC_SystemReset();  // 重置系统
            }

            break;
        }
    }

  // 透传模式下的数据收发
data_transmission_loop:
    printf3("Entering data transmission loop...\r\n");
	printf3("POST /root/code/9030/data HTTP/1.1\r\n");
    while (1) {
		char buf1[200] = {0};
        char ch = 0;
        BaseType_t ret = xQueueReceive(queue, &ch, pdMS_TO_TICKS(1000));

        if (ret == pdPASS) {
            buf1[strlen(buf1)] = ch;
            // 缓冲区满时清空
            if (strlen(buf1) >= sizeof(buf1) - 1) {
                memset(buf1, 0, sizeof(buf1));
            }
        }

        // 可以添加定期发送数据的逻辑	
			getMSG(buf1);
			printf3("%s\r\n",buf1);
			char *str1 = "POST /root/code/9030/data HTTP/1.1";
			printf2("%s", str1);
			printf2("%s\r\n",buf1);
			vTaskDelay(pdMS_TO_TICKS(3000));
    }
}

#define RESET_PRESS_THRESHOLD 5000
// 按键检测任务
void vKeyResetTask(void *pvParameters) {
    for (;;) {
        // 检查按键是否被按下
        if (reset_key_pressed) {
            reset_press_time += 100; // 每100ms增加一次计时

            // 长按超过阈值，触发系统复位
            if (reset_press_time >= RESET_PRESS_THRESHOLD) {
                Flash_ErasePage(FLASH_START_ADDR);
                // 可以在这里添加复位前的清理工作
                printf3("Long press detected, resetting system...\r\n");
                // 清除Flash配置标志（可选，根据需求决定）
                flash_config.is_configured = 0;
                Flash_WriteConfig(&flash_config);
                exit_transparent_mode() ;
                // 触发系统复位
                NVIC_SystemReset();
            }
        }

        vTaskDelay(pdMS_TO_TICKS(100)); // 100ms检测一次
    }
}



int main(void) {
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4);
    USART1_Init();
    USART2_Init();
    USART3_Init();
    ResetKey_Init();
	AD_Init();
    init_flash_config();
    queue = xQueueCreate(100, 1);
    printf3("System started\r\n");
	printf3("ready\r\n");
    // 如果已有配置，显示保存的SSID
    if (flash_config.is_configured) {
        Flash_ReadConfig(&flash_config);
    }
	
    xTaskCreate(task1, "Task1", configMINIMAL_STACK_SIZE * 8, NULL, tskIDLE_PRIORITY + 1, NULL);
    xTaskCreate(vKeyResetTask, "KeyResetTask", configMINIMAL_STACK_SIZE * 2,NULL, tskIDLE_PRIORITY + 1, NULL);
    vTaskStartScheduler();

    // 不会执行到这里
    while (1);
}

void convert(const char* in, char* out) {
    int i = 0, j = 0;
    char ssid[64] = {0};
    char pwd[64] = {0};
 

    // 跳过开头的'!'（如果存在）
    if (in[0] == '!') {
        i = 1;
    }

    // 提取SSID（直到遇到'='）
    while (in[i] != '\0' && in[i] != '=') {
        // 只保留字母、数字和合法字符（可根据需求调整）
        if ((in[i] >= 'A' && in[i] <= 'Z') ||
                (in[i] >= 'a' && in[i] <= 'z') ||
                (in[i] >= '0' && in[i] <= '9') ||
                in[i] == '_' || in[i] == '-') {
            ssid[j++] = in[i];
        }

        i++;
    }

    // 跳过'='
    if (in[i] == '=') {
        i++;
    }

    // 提取Password（直到遇到'!'或字符串结束）
    j = 0;

    while (in[i] != '\0' && in[i] != '!') {
        // 只保留字母、数字和合法字符
        if ((in[i] >= 'A' && in[i] <= 'Z') ||
                (in[i] >= 'a' && in[i] <= 'z') ||
                (in[i] >= '0' && in[i] <= '9') ||
                in[i] == '_' || in[i] == '-') {
            pwd[j++] = in[i];
        }

        i++;
    }

    // 手动添加字符串终止符
    ssid[sizeof(ssid) - 1] = '\0';
    pwd[sizeof(pwd) - 1] = '\0';

    // 生成正确的AT指令
    sprintf(out, "AT+CWJAP_DEF=\"%s\",\"%s\"\r\n", ssid, pwd);
}
